package org.sunxin.ch04.servlet;

import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
import java.sql.*;

public class CreateAccountServlet extends HttpServlet
{
    private String url;
    private String user;
    private String password;
    
    public void init() throws ServletException
    {  
    	/**
    	 * 通过 servlet上下文获得数据库连接参数
    	 */
        ServletContext sc=getServletContext();
        String driverClass=sc.getInitParameter("driverClass");
        url=sc.getInitParameter("url");
        user=sc.getInitParameter("user");
        password=sc.getInitParameter("password");
        try
        {
            Class.forName(driverClass);
        }
        catch(ClassNotFoundException ce)
        {
            throw new ServletException("加载数据库驱动失败！");
        }
    }
    
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
               throws ServletException,IOException
    {
        Connection conn=null;
        Statement stmt=null;
        PreparedStatement pstmt=null;
        try
        {
            conn=DriverManager.getConnection(url,user,password);
            stmt=conn.createStatement();
            
            stmt.executeUpdate("create table account(userid VARCHAR(10) not null primary key,balance FLOAT(6,2)) ENGINE=InnoDB");
            
            pstmt=conn.prepareStatement("insert into account values(?,?)");
            
            pstmt.setString(1,"甲");
            pstmt.setFloat(2,500.00f);
            pstmt.executeUpdate();
            
            pstmt.setString(1,"乙");
            pstmt.setFloat(2,200.00f);
            pstmt.executeUpdate();
            
            resp.setContentType("text/html;charset=GBK");
            PrintWriter out=resp.getWriter();
            out.println("创建account表成功!");
            out.close();
        }
        catch(SQLException se)
        {
            se.printStackTrace();
        }
        finally
        {
            if(stmt!=null)
            {
                try
                {
                    stmt.close();
                }
                catch(SQLException se)
                {
                    se.printStackTrace();
                }
                stmt=null;
            }
            if(pstmt!=null)
            {
                try
                {
                    pstmt.close();
                }
                catch(SQLException se)
                {
                    se.printStackTrace();
                }
                pstmt=null;
            }
            if(conn!=null)
            {
                try
                {
                    conn.close();
                }
                catch(SQLException se)
                {
                    se.printStackTrace();
                }
                conn=null;
            }
        }
    }
}